<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滑动验证</title>
    <script src="./hammer.js"></script>
    <style>
        .box{
            width: 300px;
            height: 50px;
            background-color: gray;
            border: 1px solid gray;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);

        }
        .square{
            width: 50px;
            height: 50px;
            background-color: white;
            box-sizing: border-box;
            border: 1px solid;
            position: absolute;
            transition: all 0.5s linear;
            cursor: pointer;
        }
        .box span{
            display: flex;
            justify-content: center;
            line-height:50px;
            
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="square"></div>
        <span>往右滑动！</span>
    </div>

    <script>
        let box = document.querySelector('.box');
        let square = document.querySelector('.square');
        let span = document.querySelector('span');
        //每次拖拽开始的点
        let empty  = []
        //拖拽过程中移动到的点
        let moverPoint = [];
        //上一次拖拽元素的位置
        let currentPos = {
            x: 0
        }

        square.addEventListener('touchstart',function(e) {
            //记录下开始触摸点的坐标信息
            empty.x = e.changedTouches[0].pageX;
        })
        
        box.addEventListener('touchmove',function(e) {
            //阻止浏览器默认行为
            e.preventDefault();
            //计算每次移动时，与触摸起始点的距离
            moverPoint.x = e.changedTouches[0].pageX - empty.x;
            //判断小盒子0 >= 250之间的距离超过就返回完成，没有超过就回到0 
            if(moverPoint.x >= 0 && moverPoint.x <= 250){
                //样式左边拖拽移动的点
                square.style.left = moverPoint.x + 'px';
            }else{
                return;
            }
        })

        box.addEventListener('touchend',function(e) {
            //拖拽元素位置的横轴 = 拖拽过程的点
            currentPos.x = moverPoint.x;
            //判断小于200的时候返回0，否则就返回css样式
            if(moverPoint.x < 200){
                square.style.left = 0;
            }else{
                box.style.backgroundColor = 'rgb(103, 145, 101)';
                span.innerHTML = 'perfect!'
                square.style.left = '250px';
            }
        })
    </script>
</body>
</html>